/*
 * @Author: Pure <305737824@qq.com>
 * @CreateTime: 2021-06-19 10:53:40
 * @LastEditors: Pure <305737824@qq.com>
 * @LastEditTime: 2022-03-18 17:34:18
 * @Description: http 请求封装
 */
import Axios from 'axios';
import Flat from 'flat';
import {
  omitBy,
  isNil,
  isArray,
} from 'lodash';

import { notification as Notification, } from './resetNotification';
import Store from '@/store';

const RESPONSE_CODE = {
  // 请求成功
  SUCESS: 0,
  // 登录过期
  ACCESS_TOKEN_EXPIRED: -100,
};

const service = Axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 15000,
});

service.interceptors.request.use(
  config => {
    console.log('Fetch:', config.url);
    const accessToken = Store.state['login'].accessToken;
    if (accessToken) {
      config.headers['token'] = accessToken;
    }
    config.transformRequest = [function (data) {
      if (data instanceof FormData) {
        return data;
      }
      let flatData = Flat(data, {
        maxDepth: 2,
        safe: true,
      });
      flatData = omitBy(flatData, isNil);
      const formData = new FormData();
      for (const key in flatData) {
        if (isArray(flatData[key])) {
          formData.append(key, JSON.stringify(flatData[key]));
        } else {
          formData.append(key, flatData[key]);
        }
      }
      return formData;
    }];
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  response => {
    const res = response.data;
    const env = response.headers['X-Env'] || response.headers['x-env'];
    if (env && Store.state['login'].env !== env) {
      Store.state['login'].env = env;
    }
    // 下载接口处理
    if (res instanceof Blob) {
      if (response.headers['content-type'] === 'application/vnd.ms-excel') {
        return res;
      } else {
        return Promise.reject('下载失败');
      }
    }
    // 普通接口处理

    switch (res.code) {
      case RESPONSE_CODE.SUCESS:
        if (Store.state['login'].accessToken) {
          // Store.dispatch('dictionary/FETCH_DEPARTMENT_LIST', res.edition.unit);
          Store.dispatch('systemDepartment/FETCH_DEPARTMENT_LIST', res.edition.unit);
          Store.dispatch('dictionary/FETCH_ENGINEER_LIST', res.edition.user);
          Store.dispatch('dictionary/FETCH_DIC_LIST', res.edition.dic);
        }
        return res.body;
      case RESPONSE_CODE.ACCESS_TOKEN_EXPIRED:
        return Store.dispatch('login/REFRESH', Store.state['login'].refreshToken).then(
          () => {
            return service(response.config);
          }, () => {
            Notification({
              title: '登录异常',
              message: res.msg,
              type: 'error',
            });
            // location.reload();
          }
        );
      default:
        return Promise.reject(res.msg);
    }
  },
  error => {
    console.log(JSON.stringify(error));
    if (error?.code === 'ECONNABORTED') {
      Notification({
        title: '失败',
        message: '网络超时',
        type: 'error',
      });
      return Promise.reject();
    }
    if (error?.response?.status === 404) {
      Notification({
        title: '接口错误',
        message: '访问了一个后台不支持的接口:' + error.config.url,
        type: 'error',
      });
      return Promise.reject();
    }
    if (error?.response?.status === 500) {
      Notification({
        title: '失败',
        message: '网络错误',
        type: 'error',
      });
      return Promise.reject();
    } else {
      Notification({
        title: '失败',
        message: error,
        type: 'error',
      });
      return Promise.reject();
    }
  }
);
export default service;
